package com.ruoyi.web.core.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.prod.entity.po.BaseEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 功能描述：
 * 更新公共字段
 */
@Slf4j
@Component
public class MetaHandler implements MetaObjectHandler {

    /**
     * 新增数据执行
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (metaObject.getOriginalObject() instanceof BaseEntity) {
            this.setFieldValByName("delFlag", "0", metaObject);

            this.setFieldValByName("createId", user.getUserId(), metaObject);
            this.setFieldValByName("createBy", user.getNickName(), metaObject);
            this.setFieldValByName("createDeptId", user.getDeptId(), metaObject);
            this.setFieldValByName("createDept", user.getDept().getDeptName(), metaObject);
            this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);

            this.setFieldValByName("updateId", user.getUserId(), metaObject);
            this.setFieldValByName("updateBy", user.getNickName(), metaObject);
            this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        }
    }

    /**
     * 更新数据执行
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (metaObject.getOriginalObject() instanceof BaseEntity) {
            this.setFieldValByName("updateId", user.getUserId(), metaObject);
            this.setFieldValByName("updateBy", user.getNickName(), metaObject);
            this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        }
    }
}
